package com.wyz.note.project.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyz.note.project.demo.mapper.UserInfoMapper;
import com.wyz.note.project.demo.pojo.UserInfo;
import com.wyz.note.project.demo.service.UserInfoExtendService;
import com.wyz.note.project.demo.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * <p>
 * 用户基础信息表 服务实现类
 * </p>
 *
 * @author Wei yz
 * @since 2022-01-19
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    private static final Logger log = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Override
    public Object add() {
        List<UserInfo> userInfoList = db();
        try {
            log.info("数据总长度 ==> {}", userInfoList.size());
            log.info("开始执行");
            int ths = 5;
            //创建固定线程个数为十个的线程池
            ExecutorService executorService = newFixedThreadPool(ths);
            for (int i = 0; i < ths; i++) {
                // 截取数据片段
                final List<UserInfo> nList = userInfoList.subList(userInfoList.size() / ths * i, userInfoList.size() / ths * (i + 1));
                log.info("数据片段[{}] ==> 大小：{}", i, nList.size());
                executorService.execute(new UserTaskService(nList,userInfoExtendService));
            }
            //关闭线程池
            executorService.shutdown();
            log.info("执行结束");
            return "保存成功";
        } catch (Throwable e) {
            log.info("保存失败 ==> {}", e);
            return "保存失失败 ==> " + e.getMessage();
        }
    }

    private List<UserInfo> db() {
        List<UserInfo> userInfoList = new LinkedList<>();
        for (int i = 0; i < 100000; i++) {
            userInfoList.add(new UserInfo()
                    .setId("P" + UUID.randomUUID().toString().replaceAll("-", ""))
                    .setName("张三-" + i)
                    .setPassword("p+" + i)
                    .setUsername("Z-" + i)
                    .setPhone("PHONE" + i)
                    .setDeleted(0)
                    .setEmail("8652" + i + "@qq.com"));
        }
        return userInfoList;
    }
}
